<!--
 * @Description: 
 * @Version: 1.0
 * @Author: Will
 * @Date: 2022-02-08 08:48:53
 * @LastEditors: MarsLay 331412466@qq.com
 * @LastEditTime: 2023-03-07 14:10:35
 * @FilePath: \smart-sports-managee:\project\autopilot\components\toUpdate\toUpdate.vue
 * Copyright (C) 2022 Will. All rights reserved.
-->
<template>
  <view class="update">
    <view class="infos">
      <view class="title">发现新版本</view>
      <view class="txt" v-if="!is_download">
        <!-- <block v-for="(item, i) in txt" :key="item.value">
                <view>{{ i + 1 }}.{{ item.value }}</view>
              </block> -->
        <rich-text :nodes="txt"></rich-text>
      </view>
      <view class="txt2" v-else>
        <progress class="pro" :percent="percent" :show-info="false" stroke-width="3" />
        <view v-if="percent < 100">下载进度：{{ percent }}%</view>
        <view v-else>下载完成,等待安装后重启</view>
      </view>
      <view class="btns" v-if="!is_download">
        <view class="ok" @click="ok">确认升级</view>
        <view class="cancel" @click="close">取消升级</view>
      </view>
    </view>
    <view class="close" @click="close" v-if="close_show">
      <icon type="cancel" size="26" color="#fff" />
    </view>
  </view>
</template>

<script>
import { api } from "@/api/common"
export default {
  name: "",
  components: {},
  props: {
    close_show: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      is_download: false,
      percent: 0,
      openUrl: '',
      txt: ''
    };
  },
  computed: {},
  watch: {},
  onLoad() {
  },
  created() {

  },
  onShow() { },
  mounted() {

  },
  methods: {
    close() {
      this.$emit('update', { state: 0 })
    },
    ok() {
      this.is_download = true
      this.updata()
    },
    checkUpdata() {
      this.percent = 0
      // 模拟有更新
      // this.$emit('update', { state: 1 })
      // this.checkVersionUpdate({ version: '1.0.0' })
      // return

      // #ifdef APP-PLUS
      plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => {
        this.version = wgtinfo.version;
        console.log("版本号", this.version);
        this.checkVersionUpdate({
          version: this.version,
        });
      });
      // #endif
    },
    async checkVersionUpdate(obj) {
      let phoneVer = "";
      let newVer = "";
      phoneVer = this.transArr(obj.version);

      return api.versionlist({ from: "APP" }).then((res) => {
        let temp = res.data.newest;
        this.txt = temp.info
        console.log(res.data);
        if (!temp.ver) {
          this.$util.tip({ title: `已是最新版本:${this.version}` });
          return;
        }
        // #ifdef APP-PLUS
        newVer = this.transArr(temp.ver);
        if (Number(newVer) > Number(phoneVer)) {
          this.openUrl = plus.os.name == "iOS" ? temp.ios_links : temp.apkpath;


          if (plus.os.name == "iOS") {
            return;
          }
          this.$emit('update', { state: 1 })
        } else {
          this.$util.tip({ title: `已是最新版本:${this.version}` });
        }
        // #endif
      });

    },
    transArr(str) {
      let arr = str.split(".");
      let newNum = "";
      for (let i = 0; i < arr.length; i++) {
        newNum = newNum + String(arr[i]);
      }
      return newNum;
    },
    updata() {
      let _that = this;
      this.downloadTask = uni.downloadFile({
        url: this.openUrl, // 下载资源的 url
        success: (downloadResult) => {
          // console.log(downloadResult.tempFilePath);
          if (downloadResult.statusCode === 200) {
            /* 安装应用, 要安装的文件路径(downloadResult.tempFilePath) 
            force 是否强制安装
            true表示强制安装，不进行版本号的校验；false则需要版本号校验，
            如果将要安装应用的版本号不高                
            于现有应用的版本号则终止安装，并返回安装失败。 仅安装wgt和wgtu时生效，默认值 false。
            */
            plus.runtime.install(
              downloadResult.tempFilePath,
              {
                force: true,
              },
              function () {

                // 应用热重启，重新启动进入首页。
                plus.runtime.restart();
                // isUpload = false;
                console.log("安装成功", "install success...");
              },
              function (e) {
                console.error("安装失败", "install fail...");
              }
            );
          }
        },
      });

      this.downloadTask.onProgressUpdate((res) => {
        _that.percent = res.progress;
        console.log("下载进度" + _that.percent);
        // console.log("已经下载的数据长度" + res.totalBytesWritten);
        // console.log(
        //   "预期需要下载的数据总长度" + res.totalBytesExpectedToWrite
        // );
        if (res.progress >= 100) {
          // _that.$emit('update', { state: 2 })
        }
        // 测试条件，取消下载任务。
        if (res.progress > 50) {
          // this.downloadTask.abort();
        }
      });
    },
  },

};
</script>

<style lang="less" scoped>
.update {
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.infos {
  background: #fff;
  border-radius: 30upx;
  // padding: 30upx 0;
  width: 90%;
  height: 30%;
}

.title {
  font-size: 30upx;
  height: 60upx;
  text-align: center;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  .border-1px();
}

.txt {
  height: calc(100% - 120upx);
  overflow-y: auto;
  padding: 20upx;
  font-size: 28upx;
  color: #c7c7c8;
  // .border-1px();
}

.txt2 {
  height: calc(100% - 120upx);
  padding: 20upx;
  font-size: 28upx;
  color: #c7c7c8;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  .pro {
    width: 100%;
  }
}

.btns {
  font-size: 26upx;
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  align-items: center;
  height: 60upx;
  padding: 0 40upx;

  .ok {
    background: #1ca9ff;
    border: 1px solid #1ca9ff;
    padding: 6upx 20upx;
    border-radius: 10upx;
    color: #fff;
    margin: 0 10upx;
  }

  .cancel {
    background: #fff;
    color: #c7c7c8;
    padding: 6upx 20upx;
    border-radius: 10upx;
    border: 1px solid #c7c7c8;
    margin: 0 10upx;
  }
}

.close {
  margin-top: 20upx;
}
</style>